//
//  KeychainTool.m
//  Interview
//
//  Created by gaoyu on 2019/1/15.
//  Copyright © 2019年 Gy. All rights reserved.
//

#import "KeychainTool.h"

NSString * const KEY_UDID_INSTEAD = @"com.television.app.kaychain";

@implementation KeychainTool

// 获取设备的UDID
+(NSString *)getDeviceIDInKeychain {
    NSString *getUDIDInKeychain = (NSString *)[[self class] getUDIDByKey:KEY_UDID_INSTEAD];
    
    NSLog(@"从keychain中获取到的 UDID_INSTEAD %@",getUDIDInKeychain);
    
    if (!getUDIDInKeychain ||[getUDIDInKeychain isEqualToString:@""]||[getUDIDInKeychain isKindOfClass:[NSNull class]]) {
        CFUUIDRef puuid = CFUUIDCreate( nil );
        CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
        NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
        CFRelease(puuid);
        CFRelease(uuidString);
        NSLog(@"\n \n \n _____重新存储 UUID _____\n \n \n  %@",result);
        [[self class] save:KEY_UDID_INSTEAD data:result];
        getUDIDInKeychain = (NSString *)[[self class] getUDIDByKey:KEY_UDID_INSTEAD];
    }
    NSLog(@"最终 ———— UDID_INSTEAD %@",getUDIDInKeychain);
    return getUDIDInKeychain;
}

// 保存UDID
+ (void)save:(NSString *)key data:(id)data {
    //Get search dictionary
    NSMutableDictionary *keychainQuery = [[self class] getKeychainForConditionsWithUDIDkey:key];
    //Delete old item before add new item
    SecItemDelete((CFDictionaryRef)keychainQuery);
    //Add new object to search dictionary(Attention:the data format)
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];
    //Add item to keychain with the search dictionary
    SecItemAdd((CFDictionaryRef)keychainQuery, NULL);
}

// 获取UDID
+(id)getUDIDByKey:(NSString *)key{
    
    // 查询条件
    NSMutableDictionary *conditions = [[self class] getKeychainForConditionsWithUDIDkey:key];
    
    // item 返回类型
    [conditions setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    // 返回首条item
    [conditions setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    
    id result = nil;
    
    // 查询keychain的item
    
    CFDataRef keyData = NULL;
    
    OSStatus status = SecItemCopyMatching((CFDictionaryRef)conditions, (CFTypeRef *)&keyData);
    
    if (status == noErr) {
        @try {
            result = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData*)keyData];
        } @catch (NSException *exception) {
            NSLog(@"Unarchive of %@ failed: %@", key, exception);
        } @finally {
        }
    }
    
    if (keyData) {
        CFRelease(keyData);
    }
    
    return result;
}

// 获取keychain条件
+(NSMutableDictionary *)getKeychainForConditionsWithUDIDkey:(NSString *)key{
    
    // key(一般密码、唯一身份、属性(共4中，这里是两种))
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:(id)kSecClassGenericPassword,(id)kSecClass,key,(id)kSecAttrService,key,(id)kSecAttrAccount,kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible, nil];
}


@end
